package com.sitech.ibnms.c3p.task.aspect;

import com.sitech.ibnms.c3p.domain.*;
import com.sitech.ibnms.c3p.mappers.C3pIspReportMapper;
import com.sitech.ibnms.c3p.mappers.C3pNoticeMapper;
import com.sitech.ibnms.c3p.mappers.C3pTaskMapper;
import com.sitech.ibnms.c3p.mappers.C3pTaskNodeMapper;
import com.sitech.ibnms.c3p.task.notice.NoticeService;
import com.sitech.ibnms.c3p.util.C3pConstants;
import com.sitech.ismp.workflow.domain.Task;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.StringWriter;
import java.util.*;

/**
 * Created by 59849 on 2016/1/8.
 */
@Component
public class SQLResultToMailProcesser {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private C3pIspReportMapper ispReportMapper;
    @Autowired
    private C3pTaskNodeMapper nodeMapper;
    @Autowired
    private C3pTaskMapper taskMapper;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private C3pNoticeMapper c3pNoticeMapper;

    public void process(Task task, Map params, Map outVars,ResourceAccount resourceAccount) {
        try {
            saveIspResult(task, params, outVars,resourceAccount);
            processMail(task, params, outVars);
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }

    }

    public void saveIspResult(Task task, Map<String, String> params, Map<String, String> outVars,ResourceAccount resourceAccount) {
        logger.info("SQL执行结果入库： taskId:" + task.getTaskId());
        String content = outVars.get(C3pConstants.OUTVAR_SQL_RESULT_CONTENT);
        String unitId = outVars.get(C3pConstants.OUTVAR_SQL_RESULT_UNIT_ID);

        String[] contents = content.split("\n");
        String[] unitIds = unitId.split("\n");
        List<C3pIspReport> c3pIspReports = new ArrayList<C3pIspReport>();
        String taskId = params.get(C3pConstants.PARAM_EXECUTE_RESOURCE_ID);
        String extUnitId=resourceAccount.getUnitId();
        if (contents.length > 1) {
            //将执行结果放入C3P_JSP_REPORT表中
            for (int i = 0; i < contents.length; i++) {
                C3pIspReport report = new C3pIspReport();
                report.setTaskId(params.get(C3pConstants.PARAM_C3P_TASK_ID));
                report.setScheduleId(params.get(C3pConstants.CONTEXT_SCHEDULE_ID));
                report.setCompareRst(1);
                report.setExecId(task.getSerialNo() + "");
                report.setActivityId(task.getCurrActId());
                report.setCompareDesc("SQL RESULT");
                report.setUnitId(C3pConstants.OUTVAR_SQL_RESULT_CONTENT + ":" + taskId + ":" + i);
                report.setKpiId(C3pConstants.KPI_SQL_RESULT_CONTENT);
                report.setKpiValue(contents[i]);
                report.setCreateTime(new Date());
                report.setExtUnitId(extUnitId);
                report.setPosition(unitIds.length>i?unitIds[i]:"");
                report.setDisplayMode(2);
                c3pIspReports.add(report);
            }

        }
        // sql result  size 入表
        C3pIspReport report = new C3pIspReport();
        report.setTaskId(params.get(C3pConstants.PARAM_C3P_TASK_ID));
        report.setScheduleId(params.get(C3pConstants.CONTEXT_SCHEDULE_ID));
        report.setCompareRst(1);
        report.setExecId(task.getSerialNo() + "");
        report.setActivityId(task.getCurrActId());
        report.setCompareDesc("SQL RESULT SIZE");
        report.setUnitId(C3pConstants.OUTVAR_SQL_RESULT_SIZE + ":" + taskId);
        report.setKpiId(C3pConstants.KPI_SQL_RESULT_SIZE);
        report.setKpiValue(outVars.get(C3pConstants.OUTVAR_SQL_RESULT_SIZE));
        report.setCreateTime(new Date());
        report.setExtUnitId(extUnitId);
        report.setDisplayMode(2);
        c3pIspReports.add(report);
        ispReportMapper.insert(c3pIspReports);
    }
    public void saveIspShellResult(Task task, Map<String, String> params, Map<String, String> outVars,ResourceAccount resourceAccount) {
        logger.info("Shell执行结果入库： taskId:" + task.getTaskId());
        String content = outVars.get(C3pConstants.OUTVAR_SHELL_RESULT_CONTENT);
        int displayMode =resourceAccount.getDisplayMode();
        String[] contents = content.split("\n");
        List<C3pIspReport> c3pIspReports = new ArrayList<C3pIspReport>();
        String extUnitId=resourceAccount.getUnitId();
        if (contents.length > 0) {
            //将执行结果放入C3P_JSP_REPORT表中
            for (int i = 0; i < contents.length; i++) {
                C3pIspReport report = new C3pIspReport();
                report.setTaskId(params.get(C3pConstants.PARAM_C3P_TASK_ID));
                report.setScheduleId(params.get(C3pConstants.CONTEXT_SCHEDULE_ID));
                report.setCompareRst(1);
                report.setExecId(task.getSerialNo() + "");
                report.setActivityId(task.getCurrActId());
                report.setCompareDesc("SHELL RESULT");
                report.setUnitId(C3pConstants.OUTVAR_SHELL_RESULT_CONTENT +":" + i);
                report.setKpiId(C3pConstants.KPI_SHELL_RESULT_CONTENT);
                report.setKpiValue(contents[i]);
                report.setCreateTime(new Date());
                report.setExtUnitId(extUnitId);
                report.setPosition(extUnitId);
                report.setDisplayMode(displayMode);
                c3pIspReports.add(report);
            }
            ispReportMapper.insert(c3pIspReports);
        }
    }

    public void processMail(Task task, Map<String, String> params, Map<String, String> outVars) {
        logger.info("SQL执行结果发送邮件： taskId:" + task.getTaskId());
        C3pTaskNode node = nodeMapper.queryByProcessIdAndActivityId(task.getProcessId(), task.getCurrActId());
        C3pTask c3pTask = taskMapper.findById(node.getC3pTaskId());
        String emailGroup = node.getEmailGroup();
        if (StringUtils.isBlank(emailGroup)) {
            logger.warn("[serialNo={}, activityId={}, taskId={}] SQL执行结果邮件组设值不能为空", task.getSerialNo(), task.getCurrActId(), task.getTaskId());
            return;
        }
        String title = "环节【" + node.getName() + "】SQL执行结果-任务为[" + c3pTask.getTaskName() + "]-" + task.getTaskId() + "@" + task.getSerialNo();
        String statement = outVars.get(C3pConstants.OUTVAR_SQL_STATEMENT);
        String content = outVars.get(C3pConstants.OUTVAR_SQL_RESULT_CONTENT);
        String mailContent = constructMailContent(content, statement);
        List<String> mailContentList = Arrays.asList(mailContent.split("\n"));
        for (String noticeId : emailGroup.split(",")) {
            List<C3pNotice> notices = c3pNoticeMapper.selectById(noticeId);
            for (C3pNotice c3pNotice : notices) {
                if (!StringUtils.isBlank(c3pNotice.getNoticeAddr())) {
                    for (String addr : c3pNotice.getNoticeAddr().split(",")) {
                        TbSubscribeMail mail = new TbSubscribeMail(UUID.randomUUID().toString(), addr, title);
                        noticeService.sendMail(mail, mailContentList);
                    }
                }
            }
        }

    }

    @PostConstruct
    public void initVelocity() {
        Properties p = new Properties();
        p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        p.setProperty("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(p);
    }

    public String constructMailContent(String content, String statement) {
        String[] contents = content.split("\n");
        String[] theads = contents[0].split("\t");//表头
        List<String> tableContent = Arrays.asList(contents);//表格内容
        VelocityContext context = new VelocityContext();
        context.put("contents", tableContent);
        context.put("theads", theads);
        context.put("statement", statement);
        StringWriter w = new StringWriter();
        try {
            Velocity.mergeTemplate("ispSQLResultMail.vm", "UTF-8", context, w);
        } catch (Exception e) {
            System.out.println("没有找到velocity模板文件");
            e.printStackTrace();
        }
        return w.toString();
    }
}
